package com.pxl.bi.bizmq.init;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.pxl.bi.common.BiMqConstant.*;

public class BiInitWithDLXMain {
    public static void main(String[] args) {
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("localhost");

            try (Connection connection = connectionFactory.newConnection();
                 Channel channel = connection.createChannel()) {

                // 声明死信交换机
                channel.exchangeDeclare(DLX_EXCHANGE_NAME, "fanout");

                // 创建死信队列
                String dlxQueueName = DLX_QUEUE_NAME;
                channel.queueDeclare(dlxQueueName, true, false, false, null);
                channel.queueBind(dlxQueueName, DLX_EXCHANGE_NAME, "");


                // 注册消费者，用于消费死信队列，绑定回调函数
                channel.basicConsume(dlxQueueName, false, getDeliverCallback(channel), consumerTag -> {});

                // 创建BI处理异步的交换机
                String exchangeName = BI_EXCHANGE_NAME;
                channel.exchangeDeclare(exchangeName, "direct");

                // 创建一个队列
                String queueName = BI_QUEUE_NAME;
                Map<String, Object> arguments = new HashMap<>();
                arguments.put("x-dead-letter-exchange", DLX_EXCHANGE_NAME);
                //因为死信交换机类型是fanout，所以路由键值可以不要
//                arguments.put("x-dead-letter-routing-key", DLX_QUEUE_NAME);
                channel.queueDeclare(queueName, true, false, false, arguments);
                channel.queueBind(queueName, exchangeName, BI_ROUTING_KEY);
            }

        } catch (Exception e) {
            System.out.println("RabbitMQ 初始化失败：" + e.getMessage());
        }
    }

    private static DeliverCallback getDeliverCallback(Channel channel) {
        return (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            // 处理消息
            System.out.println(" [死信] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");

            // 手动确认消息
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
    }
}
